﻿using System;
using System.Collections.Generic;
using System.Linq;
using BFlatCompile.Nodes;

namespace BFlatCompile.Serializer
{
	internal static class Phase11GetAllThingsAndSetId
	{
		// This will also set an ID indicating the 1-based index on each of these items
		// Properties will have two ID fields for getter and setter
		// The reason 1-index instead of 0-index is used is so that 0 can represent null.
		// e.g. static constructor not present or a method parameter doesn't have a default value.
		public static void Do(IList<Class> allClasses, Things things)
		{
			foreach (Class c in allClasses)
			{
				GetAllThings(c, things);
			}
		}

		private static void GetAllThings(Class c, Things things)
		{
			foreach (Method m in c.Methods)
			{
				if (m.IsStatic)
				{
					things.StaticMethods.Add(m);
					m.ID = things.StaticMethods.Count;
				}
				else
				{
					things.Methods.Add(m);
					m.ID = things.Methods.Count;
				}

				foreach (MethodParam mp in m.Params)
				{
					if (mp.Value != null)
					{
						things.MethodParamValues.Add(mp);
					}
				}
			}

			foreach (Constructor ctor in c.Constructors)
			{
				if (ctor.IsStatic)
				{
					things.StaticConstructors.Add(ctor);
					ctor.ID = things.StaticConstructors.Count;
				}
				else
				{
					things.Constructors.Add(ctor);
					ctor.ID = things.Constructors.Count;
				}

				foreach (MethodParam mp in ctor.Params)
				{
					if (mp.Value != null)
					{
						things.MethodParamValues.Add(mp);
					}
				}
			}

			foreach (Property p in c.Properties)
			{
				List<Property> getters;
				List<Property> setters;
				if (p.IsStatic)
				{
					getters = things.StaticPropertyGetters;
					setters = things.StaticPropertySetters;
				}
				else
				{
					getters = things.PropertyGetters;
					setters = things.PropertySetters;
				}

				if (p.Getter != null)
				{
					getters.Add(p);
					p.GetterID = getters.Count;
				}

				if (p.Setter != null)
				{
					setters.Add(p);
					p.SetterID = setters.Count;
				}
			}
		}
	}
}
